<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色与员工管理系统</title>
    <!-- 引入Vue -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- 引入Element UI -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
        .app-container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            margin: 0;
            padding: 0;
        }
        
        .main-layout {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        
        .role-sidebar {
            width: 200px;
            background-color: #f5f7fa;
            border-right: 1px solid #e4e7ed;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .view-employee-btn {
            margin: 15px;
            width: calc(100% - 30px);
        }
        
        .role-list-wrapper {
            flex: 1;
            overflow-y: auto;
            padding-bottom: 15px;
        }
        
        .role-collapse {
            margin: 0 15px;
            border: none;
        }
        
        .el-collapse-item__content {
            padding-bottom: 0;
        }
        
        .custom-role-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
        }
        
        .role-menu {
            border: none;
            background-color: transparent;
        }
        
        .role-menu .el-menu-item {
            padding: 0 20px;
            height: 40px;
            line-height: 40px;
        }
        
        .role-actions {
            float: right;
            margin-right: -10px;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .el-menu-item:hover .role-actions {
            opacity: 1;
        }
        
        .content-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f5f7fa;
        }
        
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .tab-content {
            padding: 15px 0;
        }
        
        .role-assignment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .employee-search {
            width: 300px;
        }
        
        .role-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }
        
        .el-dialog__body {
            max-height: 60vh;
            overflow-y: auto;
        }
        
        .role-form-item {
            margin-bottom: 20px;
        }
        
        .role-category {
            margin-bottom: 15px;
        }
        
        .role-category-title {
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .employee-selection-list {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            padding: 10px;
        }
        
        .employee-selection-item {
            margin-bottom: 8px;
        }
        
        .permission-tree {
            margin-top: 15px;
        }
        
        .delete-disabled-tooltip {
            cursor: not-allowed;
        }
        
        .add-employee-tabs {
            margin-bottom: 15px;
        }
        
        .department-section {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px dashed #e4e7ed;
        }
        
        .department-section:last-child {
            border-bottom: none;
        }
        
        .department-title {
            font-weight: bold;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }
        
        .department-count {
            color: #606266;
            font-weight: normal;
            margin-left: 5px;
            font-size: 12px;
        }
        
        .department-employees {
            margin-left: 20px;
            margin-top: 5px;
        }
        
        .add-employee-role-section {
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e4e7ed;
        }
    </style>
</head>
<body>
    <div id="app" class="app-container">
        <el-row :gutter="0" class="main-layout">
            <!-- 左侧角色区域 -->
            <el-col :span="6" class="role-sidebar">
                <!-- 按员工查看按钮 -->
                <el-button 
                    type="primary" 
                    icon="el-icon-user" 
                    class="view-employee-btn"
                    @click="switchToEmployeeView"
                >
                    按员工查看
                </el-button>
                
                <!-- 角色列表 -->
                <div class="role-list-wrapper">
                    <!-- 预设角色 -->
                    <el-collapse v-model="activeCollapse" class="role-collapse">
                        <el-collapse-item title="预设角色" name="preset">
                            <el-menu 
                                :default-active="currentRole.id.toString()" 
                                class="role-menu"
                                @select="handleRoleSelect"
                            >
                                <el-menu-item 
                                    v-for="role in presetRoles" 
                                    :key="role.id" 
                                    :index="role.id.toString()"
                                >
                                    {{ role.name }}
                                </el-menu-item>
                            </el-menu>
                        </el-collapse-item>
                        
                        <!-- 自定义角色 -->
                        <el-collapse-item name="custom">
                            <template slot="title">
                                <div class="custom-role-header">
                                    <span>自定义角色</span>
                                    <el-button 
                                        type="text" 
                                        icon="el-icon-plus" 
                                        size="mini"
                                        @click="openAddRoleDialog"
                                    ></el-button>
                                </div>
                            </template>
                            <el-menu 
                                :default-active="currentRole.id.toString()" 
                                class="role-menu"
                                @select="handleRoleSelect"
                            >
                                <el-menu-item 
                                    v-for="role in customRoles" 
                                    :key="role.id" 
                                    :index="role.id.toString()"
                                >
                                    <span class="role-name">{{ role.name }}</span>
                                    <div class="role-actions">
                                        <el-button 
                                            type="text" 
                                            icon="el-icon-edit" 
                                            size="mini"
                                            @click.stop="openEditRoleDialog(role)"
                                        ></el-button>
                                        
                                        <!-- 删除按钮：根据是否有关联员工决定是否可点击 -->
                                        <template v-if="hasAssociatedEmployees(role.id)">
                                            <el-tooltip 
                                                placement="right" 
                                                content="该角色已关联员工，无法删除"
                                                effect="dark"
                                            >
                                                <el-button 
                                                    type="text" 
                                                    icon="el-icon-delete" 
                                                    size="mini"
                                                    disabled
                                                    class="delete-disabled-tooltip"
                                                ></el-button>
                                            </el-tooltip>
                                        </template>
                                        <template v-else>
                                            <el-button 
                                                type="text" 
                                                icon="el-icon-delete" 
                                                size="mini"
                                                @click.stop="openDeleteRoleConfirm(role)"
                                            ></el-button>
                                        </template>
                                    </div>
                                </el-menu-item>
                            </el-menu>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </el-col>
            
            <!-- 右侧内容区域 -->
            <el-col :span="18" class="content-area">
                <!-- 角色详情视图 -->
                <div v-if="currentView === 'role'">
                    <el-card>
                        <div slot="header" class="card-header">
                            <h2>角色详情</h2>
                        </div>
                        
                        <el-descriptions column="3" border class="role-info">
                            <el-descriptions-item label="角色名称">{{ currentRole.name }}</el-descriptions-item>
                            <el-descriptions-item label="创建时间">{{ currentRole.createTime }}</el-descriptions-item>
                            <el-descriptions-item label="创建人">{{ currentRole.creator }}</el-descriptions-item>
                            <el-descriptions-item label="角色描述" :span="3">{{ currentRole.description }}</el-descriptions-item>
                            <el-descriptions-item label="关联员工数量">{{ currentRole.employeeCount }}</el-descriptions-item>
                        </el-descriptions>
                        
                        <!-- 角色分配和关联权限的Tab切换 -->
                        <el-tabs v-model="activeTab" class="role-tabs">
                            <el-tab-pane label="角色分配" name="assignment" class="tab-pane">
                                <div class="tab-content">
                                    <div class="role-assignment-header">
                                        <h3>已分配该角色的员工</h3>
                                        <el-button 
                                            type="primary" 
                                            icon="el-icon-plus" 
                                            size="mini"
                                            @click="openAddEmployeeToRoleDialog"
                                        >
                                            添加员工
                                        </el-button>
                                    </div>
                                    
                                    <el-table
                                        :data="employeesWithCurrentRole"
                                        border
                                        style="width: 100%;"
                                        v-loading="loadingAssignment"
                                    >
                                        <el-table-column
                                            prop="name"
                                            label="员工姓名"
                                            width="180"
                                        ></el-table-column>
                                        <el-table-column
                                            prop="department"
                                            label="部门"
                                            width="180"
                                        ></el-table-column>
                                        <el-table-column
                                            prop="roles"
                                            label="角色"
                                        >
                                            <template slot-scope="scope">
                                                <div class="role-tags">
                                                    <el-tag 
                                                        v-for="role in scope.row.roles" 
                                                        :key="role.id"
                                                        :type="getRoleTagType(role.id)"
                                                        size="small"
                                                    >
                                                        {{ role.name }}
                                                    </el-tag>
                                                </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            label="操作"
                                            width="100"
                                        >
                                            <template slot-scope="scope">
                                                <el-button 
                                                    type="text" 
                                                    size="small"
                                                    style="color: #F56C6C;"
                                                    @click="openRemoveEmployeeFromRoleConfirm(scope.row)"
                                                >
                                                    移除
                                                </el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    
                                    <div v-if="employeesWithCurrentRole.length === 0" style="text-align: center; padding: 30px;">
                                        暂无员工分配此角色，点击"添加员工"按钮进行分配
                                    </div>
                                </div>
                            </el-tab-pane>
                            
                            <el-tab-pane label="关联权限" name="permissions" class="tab-pane">
                                <div class="tab-content">
                                    <h3>角色拥有的权限</h3>
                                    <el-tree
                                        :data="currentRolePermissions"
                                        :props="treeProps"
                                        show-checkbox
                                        node-key="id"
                                        default-expand-all
                                        :disabled="true"
                                        class="permission-tree"
                                    ></el-tree>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </el-card>
                </div>
                
                <!-- 员工列表视图 -->
                <div v-if="currentView === 'employee'">
                    <el-card>
                        <div slot="header" class="card-header">
                            <h2>员工列表</h2>
                            <div style="display: flex; align-items: center;">
                                <el-input
                                    placeholder="搜索员工..."
                                    prefix-icon="el-icon-search"
                                    v-model="employeeSearchQuery"
                                    class="employee-search"
                                    style="width: 300px; margin-right: 10px;"
                                ></el-input>
                                <el-button 
                                    type="primary" 
                                    icon="el-icon-plus" 
                                    @click="openAddNewEmployeeDialog"
                                >
                                    添加员工
                                </el-button>
                            </div>
                        </div>
                        
                        <el-table
                            :data="filteredEmployees"
                            border
                            style="width: 100%;"
                        >
                            <el-table-column
                                prop="name"
                                label="员工姓名"
                                width="180"
                            ></el-table-column>
                            <el-table-column
                                prop="department"
                                label="部门"
                                width="180"
                            ></el-table-column>
                            <el-table-column
                                prop="roles"
                                label="角色"
                            >
                                <template slot-scope="scope">
                                    <div class="role-tags">
                                        <el-tag 
                                            v-for="role in scope.row.roles" 
                                            :key="role.id"
                                            :type="getRoleTagType(role.id)"
                                            size="small"
                                        >
                                            {{ role.name }}
                                        </el-tag>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="操作"
                                width="200"
                            >
                                <template slot-scope="scope">
                                    <el-button 
                                        type="text" 
                                        size="small"
                                        @click="openEditEmployeeRoleDialog(scope.row)"
                                    >
                                        编辑
                                    </el-button>
                                    <el-button 
                                        type="text" 
                                        size="small"
                                        style="color: #F56C6C;"
                                        @click="openClearEmployeeRolesConfirm(scope.row)"
                                    >
                                        清空角色
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        
                        <div style="margin-top: 15px; text-align: right;">
                            <el-pagination
                                background
                                :current-page="1"
                                :page-size="10"
                                :total="employees.length"
                                layout="total, prev, pager, next"
                            ></el-pagination>
                        </div>
                    </el-card>
                </div>
            </el-col>
        </el-row>
        
        <!-- 新增角色弹窗 -->
        <el-dialog
            title="新增自定义角色"
            :visible.sync="addRoleDialogVisible"
            width="400px"
            :before-close="handleAddRoleDialogClose"
        >
            <el-form :model="newRoleForm" :rules="roleFormRules" ref="newRoleForm">
                <el-form-item label="角色名称" prop="name" class="role-form-item">
                    <el-input v-model="newRoleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="description" class="role-form-item">
                    <el-input
                        type="textarea"
                        v-model="newRoleForm.description"
                        :rows="4"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="handleAddRoleDialogClose">取消</el-button>
                <el-button type="primary" @click="confirmAddRole">保存</el-button>
            </div>
        </el-dialog>
        
        <!-- 编辑角色弹窗 -->
        <el-dialog
            title="编辑角色"
            :visible.sync="editRoleDialogVisible"
            width="400px"
            :before-close="handleEditRoleDialogClose"
        >
            <el-form :model="editRoleForm" :rules="roleFormRules" ref="editRoleForm">
                <el-form-item label="角色名称" prop="name" class="role-form-item">
                    <el-input v-model="editRoleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="description" class="role-form-item">
                    <el-input
                        type="textarea"
                        v-model="editRoleForm.description"
                        :rows="4"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="handleEditRoleDialogClose">取消</el-button>
                <el-button type="primary" @click="confirmEditRole">保存</el-button>
            </div>
        </el-dialog>
        
        <!-- 删除角色确认弹窗 -->
        <el-dialog
            title="确认删除"
            :visible.sync="deleteRoleConfirmVisible"
            width="300px"
            :show-close="false"
        >
            <p>确定要删除"{{ roleToDelete.name }}"角色吗？</p>
            <div slot="footer">
                <el-button @click="deleteRoleConfirmVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDeleteRole">确认删除</el-button>
            </div>
        </el-dialog>
        
        <!-- 编辑员工角色弹窗 -->
        <el-dialog
            title="编辑员工角色"
            :visible.sync="editEmployeeRoleDialogVisible"
            width="400px"
            :before-close="handleEditEmployeeRoleDialogClose"
        >
            <div v-if="currentEmployee">
                <p style="margin-bottom: 15px;">员工：{{ currentEmployee.name }}</p>
                
                <div class="role-category">
                    <div class="role-category-title">预设角色</div>
                    <el-checkbox-group v-model="selectedRoleIds">
                        <el-checkbox 
                            v-for="role in presetRoles" 
                            :key="role.id"
                            :label="role.id"
                            style="display: block; margin-bottom: 8px;"
                        >
                            {{ role.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
                
                <div class="role-category">
                    <div class="role-category-title">自定义角色</div>
                    <el-checkbox-group v-model="selectedRoleIds">
                        <el-checkbox 
                            v-for="role in customRoles" 
                            :key="role.id"
                            :label="role.id"
                            style="display: block; margin-bottom: 8px;"
                        >
                            {{ role.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
            </div>
            
            <div slot="footer">
                <el-button @click="handleEditEmployeeRoleDialogClose">取消</el-button>
                <el-button type="primary" @click="confirmEditEmployeeRole">确定</el-button>
            </div>
        </el-dialog>
        
        <!-- 清空员工角色确认弹窗 -->
        <el-dialog
            title="确认清除"
            :visible.sync="clearEmployeeRolesConfirmVisible"
            width="300px"
            :show-close="false"
        >
            <p v-if="currentEmployee">确定要清除{{ currentEmployee.name }}的所有角色吗？清除后将失去相关权限。</p>
            <div slot="footer">
                <el-button @click="clearEmployeeRolesConfirmVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmClearEmployeeRoles">确认</el-button>
            </div>
        </el-dialog>
        
        <!-- 向角色添加员工弹窗 -->
        <el-dialog
            title="添加员工到角色"
            :visible.sync="addEmployeeToRoleDialogVisible"
            width="500px"
            :before-close="handleAddEmployeeToRoleDialogClose"
        >
            <div>
                <p style="margin-bottom: 15px;">角色：{{ currentRole.name }}</p>
                <p style="margin-bottom: 10px;">请选择要添加此角色的员工：</p>
                
                <div class="employee-selection-list">
                    <el-checkbox-group v-model="selectedEmployeeIds">
                        <el-checkbox 
                            v-for="employee in allEmployeesNotInRole" 
                            :key="employee.id"
                            :label="employee.id"
                            class="employee-selection-item"
                        >
                            <span>{{ employee.name }} - {{ employee.department }}</span>
                        </el-checkbox>
                    </el-checkbox-group>
                </div>
                
                <div v-if="allEmployeesNotInRole.length === 0" style="text-align: center; padding: 20px;">
                    所有员工都已拥有此角色
                </div>
            </div>
            
            <div slot="footer">
                <el-button @click="handleAddEmployeeToRoleDialogClose">取消</el-button>
                <el-button type="primary" @click="confirmAddEmployeeToRole">保存</el-button>
            </div>
        </el-dialog>
        
        <!-- 从角色移除员工确认弹窗 -->
        <el-dialog
            title="确认移除"
            :visible.sync="removeEmployeeFromRoleConfirmVisible"
            width="300px"
            :show-close="false"
        >
            <p v-if="employeeToRemove">确定要移除{{ employeeToRemove.name }}的"{{ currentRole.name }}"角色吗？</p>
            <div slot="footer">
                <el-button @click="removeEmployeeFromRoleConfirmVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmRemoveEmployeeFromRole">确认移除</el-button>
            </div>
        </el-dialog>
        
        <!-- 添加新员工弹窗 -->
        <el-dialog
            title="添加员工"
            :visible.sync="addNewEmployeeDialogVisible"
            width="600px"
            :before-close="handleAddNewEmployeeDialogClose"
        >
            <div>
                <!-- 员工选择方式Tab -->
                <el-tabs 
                    v-model="employeeSelectionTab" 
                    class="add-employee-tabs"
                    @tab-click="handleEmployeeSelectionTabChange"
                >
                    <el-tab-pane label="按部门选择" name="byDepartment"></el-tab-pane>
                    <el-tab-pane label="按员工选择" name="byEmployee"></el-tab-pane>
                </el-tabs>
                
                <!-- 按部门选择员工 -->
                <div v-if="employeeSelectionTab === 'byDepartment'">
                    <div v-for="dept in departments" :key="dept.id" class="department-section">
                        <div class="department-title">
                            <el-checkbox 
                                :label="dept.id"
                                @change="handleDepartmentSelect(dept.id, $event)"
                            >
                                {{ dept.name }}
                                <span class="department-count">({{ getDepartmentEmployeeCount(dept.id) }}人)</span>
                            </el-checkbox>
                        </div>
                        
                        <div class="department-employees">
                            <el-checkbox-group 
                                v-model="selectedEmployeeIds"
                                :disabled="true"
                            >
                                <el-checkbox 
                                    v-for="emp in getEmployeesByDepartment(dept.id)" 
                                    :key="emp.id"
                                    :label="emp.id"
                                    style="display: block; margin-bottom: 5px;"
                                >
                                    {{ emp.name }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>
                
                <!-- 按员工选择员工 -->
                <div v-if="employeeSelectionTab === 'byEmployee'">
                    <el-input
                        placeholder="搜索员工..."
                        prefix-icon="el-icon-search"
                        v-model="addEmployeeSearchQuery"
                        style="margin-bottom: 15px;"
                    ></el-input>
                    
                    <div v-for="dept in departments" :key="dept.id" class="department-section">
                        <div class="department-title">{{ dept.name }}</div>
                        
                        <div class="department-employees">
                            <el-checkbox-group v-model="selectedEmployeeIds">
                                <el-checkbox 
                                    v-for="emp in getFilteredEmployeesByDepartment(dept.id)" 
                                    :key="emp.id"
                                    :label="emp.id"
                                    style="display: block; margin-bottom: 5px;"
                                >
                                    {{ emp.name }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>
                
                <!-- 角色选择区域 -->
                <div class="add-employee-role-section">
                    <div class="role-category-title">选择角色（可多选）</div>
                    
                    <div class="role-category">
                        <div style="font-weight: bold; margin-bottom: 8px;">预设角色</div>
                        <el-checkbox-group v-model="newEmployeeRoleIds">
                            <el-checkbox 
                                v-for="role in presetRoles" 
                                :key="role.id"
                                :label="role.id"
                                style="display: inline-block; margin-right: 15px; margin-bottom: 8px;"
                            >
                                {{ role.name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                    
                    <div class="role-category">
                        <div style="font-weight: bold; margin-bottom: 8px;">自定义角色</div>
                        <el-checkbox-group v-model="newEmployeeRoleIds">
                            <el-checkbox 
                                v-for="role in customRoles" 
                                :key="role.id"
                                :label="role.id"
                                style="display: inline-block; margin-right: 15px; margin-bottom: 8px;"
                            >
                                {{ role.name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </div>
            </div>
            
            <div slot="footer">
                <el-button @click="handleAddNewEmployeeDialogClose">取消</el-button>
                <el-button type="primary" @click="confirmAddNewEmployees">保存</el-button>
            </div>
        </el-dialog>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    // 视图状态
                    currentView: 'role', // 'role' 或 'employee'
                    activeTab: 'assignment', // 'assignment' 或 'permissions'
                    
                    // 角色数据
                    presetRoles: [
                        {
                            id: 1,
                            name: '超级管理员',
                            description: '拥有系统全部权限，可以管理所有功能模块',
                            createTime: '2023-01-15 09:30:00',
                            creator: '系统默认',
                            employeeCount: '1 人'
                        },
                        {
                            id: 2,
                            name: '系统管理员',
                            description: '拥有系统大部分管理权限，可管理用户和角色',
                            createTime: '2023-01-15 09:35:00',
                            creator: '系统默认',
                            employeeCount: '1 人'
                        }
                    ],
                    customRoles: [
                        {
                            id: 3,
                            name: '部门主管',
                            description: '负责部门日常管理工作',
                            createTime: '2023-02-20 14:20:00',
                            creator: '张三',
                            employeeCount: '2 人'
                        },
                        {
                            id: 4,
                            name: '普通员工',
                            description: '执行日常工作任务',
                            createTime: '2023-02-20 14:25:00',
                            creator: '张三',
                            employeeCount: '3 人'
                        },
                        {
                            id: 5,
                            name: '财务专员',
                            description: '负责财务相关工作',
                            createTime: '2023-03-05 10:15:00',
                            creator: '李四',
                            employeeCount: '0 人' // 无关联员工，可删除
                        }
                    ],
                    currentRole: {},
                    activeCollapse: ['preset', 'custom'],
                    loadingAssignment: false,
                    
                    // 权限数据
                    rolePermissions: {
                        1: [
                            {
                                id: 101,
                                label: '用户管理',
                                children: [
                                    { id: 1011, label: '查看用户列表' },
                                    { id: 1012, label: '创建用户' },
                                    { id: 1013, label: '编辑用户' },
                                    { id: 1014, label: '删除用户' }
                                ]
                            },
                            {
                                id: 102,
                                label: '角色管理',
                                children: [
                                    { id: 1021, label: '查看角色列表' },
                                    { id: 1022, label: '创建角色' },
                                    { id: 1023, label: '编辑角色' },
                                    { id: 1024, label: '删除角色' }
                                ]
                            }
                        ],
                        2: [
                            {
                                id: 101,
                                label: '用户管理',
                                children: [
                                    { id: 1011, label: '查看用户列表' },
                                    { id: 1012, label: '创建用户' },
                                    { id: 1013, label: '编辑用户' }
                                ]
                            },
                            {
                                id: 102,
                                label: '角色管理',
                                children: [
                                    { id: 1021, label: '查看角色列表' },
                                    { id: 1022, label: '创建角色' },
                                    { id: 1023, label: '编辑角色' }
                                ]
                            }
                        ],
                        3: [
                            {
                                id: 104,
                                label: '部门员工管理',
                                children: [
                                    { id: 1041, label: '查看部门员工' },
                                    { id: 1042, label: '分配部门任务' }
                                ]
                            }
                        ],
                        4: [
                            {
                                id: 105,
                                label: '个人工作管理',
                                children: [
                                    { id: 1051, label: '查看个人任务' },
                                    { id: 1052, label: '提交工作汇报' }
                                ]
                            }
                        ],
                        5: [
                            {
                                id: 106,
                                label: '财务管理',
                                children: [
                                    { id: 1061, label: '查看财务数据' },
                                    { id: 1062, label: '提交财务报表' }
                                ]
                            }
                        ]
                    },
                    currentRolePermissions: [],
                    treeProps: {
                        children: 'children',
                        label: 'label'
                    },
                    
                    // 部门数据
                    departments: [
                        { id: 1, name: '技术部' },
                        { id: 2, name: '人事部' },
                        { id: 3, name: '财务部' },
                        { id: 4, name: '市场部' }
                    ],
                    
                    // 员工数据
                    employees: [
                        {
                            id: 1,
                            name: '张三',
                            department: '技术部',
                            departmentId: 1,
                            roles: [
                                { id: 1, name: '超级管理员' }
                            ],
                            adder: '系统默认',
                            addTime: '2023-01-20 10:00:00'
                        },
                        {
                            id: 2,
                            name: '李四',
                            department: '人事部',
                            departmentId: 2,
                            roles: [
                                { id: 2, name: '系统管理员' }
                            ],
                            adder: '张三',
                            addTime: '2023-02-05 14:30:00'
                        },
                        {
                            id: 3,
                            name: '王五',
                            department: '财务部',
                            departmentId: 3,
                            roles: [
                                { id: 3, name: '部门主管' }
                            ],
                            adder: '李四',
                            addTime: '2023-02-15 09:15:00'
                        },
                        {
                            id: 4,
                            name: '赵六',
                            department: '市场部',
                            departmentId: 4,
                            roles: [
                                { id: 4, name: '普通员工' }
                            ],
                            adder: '李四',
                            addTime: '2023-03-01 11:20:00'
                        },
                        {
                            id: 5,
                            name: '钱七',
                            department: '技术部',
                            departmentId: 1,
                            roles: [
                                { id: 4, name: '普通员工' },
                                { id: 3, name: '部门主管' }
                            ],
                            adder: '张三',
                            addTime: '2023-03-10 16:40:00'
                        },
                        {
                            id: 6,
                            name: '孙八',
                            department: '财务部',
                            departmentId: 3,
                            roles: [
                                { id: 4, name: '普通员工' }
                            ],
                            adder: '王五',
                            addTime: '2023-03-15 10:00:00'
                        }
                    ],
                    employeeSearchQuery: '',
                    
                    // 添加员工相关
                    addNewEmployeeDialogVisible: false,
                    employeeSelectionTab: 'byDepartment', // 'byDepartment' 或 'byEmployee'
                    addEmployeeSearchQuery: '',
                    selectedDepartmentIds: [],
                    selectedEmployeeIds: [],
                    newEmployeeRoleIds: [],
                    
                    // 弹窗状态
                    addRoleDialogVisible: false,
                    editRoleDialogVisible: false,
                    deleteRoleConfirmVisible: false,
                    editEmployeeRoleDialogVisible: false,
                    clearEmployeeRolesConfirmVisible: false,
                    addEmployeeToRoleDialogVisible: false,
                    removeEmployeeFromRoleConfirmVisible: false,
                    
                    // 表单数据
                    newRoleForm: {
                        name: '',
                        description: ''
                    },
                    editRoleForm: {
                        id: '',
                        name: '',
                        description: ''
                    },
                    roleFormRules: {
                        name: [
                            { required: true, message: '请输入角色名称', trigger: 'blur' }
                        ],
                        description: [
                            { required: true, message: '请输入角色描述', trigger: 'blur' }
                        ]
                    },
                    
                    // 当前操作对象
                    roleToDelete: {},
                    currentEmployee: null,
                    employeeToRemove: null,
                    selectedRoleIds: []
                };
            },
            computed: {
                // 筛选后的员工列表
                filteredEmployees() {
                    if (!this.employeeSearchQuery) {
                        return this.employees;
                    }
                    const query = this.employeeSearchQuery.toLowerCase();
                    return this.employees.filter(employee => 
                        employee.name.toLowerCase().includes(query) || 
                        employee.department.toLowerCase().includes(query) ||
                        employee.roles.some(role => role.name.toLowerCase().includes(query))
                    );
                },
                
                // 拥有当前角色的员工列表
                employeesWithCurrentRole() {
                    if (!this.currentRole.id) return [];
                    return this.employees.filter(employee => 
                        employee.roles.some(role => role.id === this.currentRole.id)
                    );
                },
                
                // 没有当前角色的员工列表（用于添加员工到角色）
                allEmployeesNotInRole() {
                    if (!this.currentRole.id) return [];
                    return this.employees.filter(employee => 
                        !employee.roles.some(role => role.id === this.currentRole.id)
                    );
                }
            },
            created() {
                // 初始化当前角色为第一个预设角色
                this.currentRole = this.presetRoles[0];
                this.currentRolePermissions = this.rolePermissions[this.currentRole.id] || [];
            },
            methods: {
                // 检查角色是否有关联员工
                hasAssociatedEmployees(roleId) {
                    return this.employees.some(employee => 
                        employee.roles.some(role => role.id === roleId)
                    );
                },
                
                // 切换到员工视图
                switchToEmployeeView() {
                    this.currentView = 'employee';
                },
                
                // 处理角色选择
                handleRoleSelect(roleId) {
                    this.currentView = 'role';
                    this.activeTab = 'assignment'; // 切换角色时默认显示角色分配Tab
                    const id = parseInt(roleId);
                    
                    // 查找选中的角色
                    const foundRole = this.presetRoles.find(role => role.id === id) || 
                                     this.customRoles.find(role => role.id === id);
                                     
                    if (foundRole) {
                        this.currentRole = foundRole;
                        this.currentRolePermissions = this.rolePermissions[this.currentRole.id] || [];
                    }
                },
                
                // 获取角色标签类型
                getRoleTagType(roleId) {
                    // 预设角色使用特定颜色，自定义角色使用默认颜色
                    if (roleId === 1) return 'primary';
                    if (roleId === 2) return 'success';
                    return '';
                },
                
                // 打开新增角色弹窗
                openAddRoleDialog() {
                    this.newRoleForm = {
                        name: '',
                        description: ''
                    };
                    this.addRoleDialogVisible = true;
                },
                
                // 关闭新增角色弹窗
                handleAddRoleDialogClose() {
                    this.$refs.newRoleForm.resetFields();
                    this.addRoleDialogVisible = false;
                },
                
                // 确认新增角色
                confirmAddRole() {
                    this.$refs.newRoleForm.validate(valid => {
                        if (valid) {
                            // 检查角色名称是否已存在
                            const nameExists = this.presetRoles.some(role => role.name === this.newRoleForm.name) ||
                                              this.customRoles.some(role => role.name === this.newRoleForm.name);
                              
                            if (nameExists) {
                                this.$message.error('角色名称已存在，请使用其他名称');
                                return;
                            }
                            
                            // 创建新角色
                            const newRole = {
                                id: Math.max(...this.presetRoles.map(r => r.id), ...this.customRoles.map(r => r.id)) + 1,
                                name: this.newRoleForm.name,
                                description: this.newRoleForm.description,
                                createTime: new Date().toLocaleString(),
                                creator: '当前用户',
                                employeeCount: '0 人'
                            };
                            
                            // 添加到自定义角色列表
                            this.customRoles.push(newRole);
                            
                            // 关闭弹窗
                            this.handleAddRoleDialogClose();
                            
                            // 显示成功消息
                            this.$message.success('角色创建成功');
                            
                            // 自动选择新创建的角色
                            this.handleRoleSelect(newRole.id.toString());
                        }
                    });
                },
                
                // 打开编辑角色弹窗
                openEditRoleDialog(role) {
                    this.editRoleForm = {
                        id: role.id,
                        name: role.name,
                        description: role.description
                    };
                    this.editRoleDialogVisible = true;
                },
                
                // 关闭编辑角色弹窗
                handleEditRoleDialogClose() {
                    this.$refs.editRoleForm.resetFields();
                    this.editRoleDialogVisible = false;
                },
                
                // 确认编辑角色
                confirmEditRole() {
                    this.$refs.editRoleForm.validate(valid => {
                        if (valid) {
                            // 检查角色名称是否已存在（排除当前角色）
                            const nameExists = this.presetRoles.some(role => role.name === this.editRoleForm.name && role.id !== this.editRoleForm.id) ||
                                              this.customRoles.some(role => role.name === this.editRoleForm.name && role.id !== this.editRoleForm.id);
                              
                            if (nameExists) {
                                this.$message.error('角色名称已存在，请使用其他名称');
                                return;
                            }
                            
                            // 更新角色信息
                            const roleIndex = this.customRoles.findIndex(r => r.id === this.editRoleForm.id);
                            if (roleIndex !== -1) {
                                this.customRoles[roleIndex].name = this.editRoleForm.name;
                                this.customRoles[roleIndex].description = this.editRoleForm.description;
                                
                                // 如果正在查看该角色，同步更新当前角色信息
                                if (this.currentRole.id === this.editRoleForm.id) {
                                    this.currentRole.name = this.editRoleForm.name;
                                    this.currentRole.description = this.editRoleForm.description;
                                }
                            }
                            
                            // 关闭弹窗
                            this.handleEditRoleDialogClose();
                            
                            // 显示成功消息
                            this.$message.success('角色更新成功');
                        }
                    });
                },
                
                // 打开删除角色确认弹窗
                openDeleteRoleConfirm(role) {
                    this.roleToDelete = { ...role };
                    this.deleteRoleConfirmVisible = true;
                },
                
                // 确认删除角色
                confirmDeleteRole() {
                    // 再次检查是否有关联员工（防止并发操作导致状态变化）
                    if (this.hasAssociatedEmployees(this.roleToDelete.id)) {
                        this.$message.error('该角色已关联员工，无法删除');
                        this.deleteRoleConfirmVisible = false;
                        return;
                    }
                    
                    // 从自定义角色列表中删除
                    const roleIndex = this.customRoles.findIndex(r => r.id === this.roleToDelete.id);
                    if (roleIndex !== -1) {
                        this.customRoles.splice(roleIndex, 1);
                        
                        // 如果删除的是当前选中的角色，切换到第一个角色
                        if (this.currentRole.id === this.roleToDelete.id) {
                            if (this.presetRoles.length > 0) {
                                this.handleRoleSelect(this.presetRoles[0].id.toString());
                            } else if (this.customRoles.length > 0) {
                                this.handleRoleSelect(this.customRoles[0].id.toString());
                            }
                        }
                    }
                    
                    // 关闭弹窗
                    this.deleteRoleConfirmVisible = false;
                    
                    // 显示成功消息
                    this.$message.success(`角色"${this.roleToDelete.name}"已删除`);
                },
                
                // 打开编辑员工角色弹窗
                openEditEmployeeRoleDialog(employee) {
                    this.currentEmployee = { ...employee };
                    // 获取当前员工的角色ID列表
                    this.selectedRoleIds = employee.roles.map(role => role.id);
                    this.editEmployeeRoleDialogVisible = true;
                },
                
                // 关闭编辑员工角色弹窗
                handleEditEmployeeRoleDialogClose() {
                    this.currentEmployee = null;
                    this.selectedRoleIds = [];
                    this.editEmployeeRoleDialogVisible = false;
                },
                
                // 确认编辑员工角色
                confirmEditEmployeeRole() {
                    if (this.currentEmployee) {
                        // 获取所有角色信息
                        const allRoles = [...this.presetRoles, ...this.customRoles];
                        
                        // 更新员工角色
                        const employeeIndex = this.employees.findIndex(e => e.id === this.currentEmployee.id);
                        if (employeeIndex !== -1) {
                            // 记录旧角色以便更新计数
                            const oldRoles = this.employees[employeeIndex].roles.map(r => r.id);
                            
                            // 设置新角色
                            this.employees[employeeIndex].roles = this.selectedRoleIds.map(roleId => {
                                const role = allRoles.find(r => r.id === roleId);
                                return { id: role.id, name: role.name };
                            });
                            
                            // 更新角色的员工计数
                            this.updateRoleEmployeeCounts(oldRoles, this.selectedRoleIds);
                        }
                        
                        // 关闭弹窗
                        this.handleEditEmployeeRoleDialogClose();
                        
                        // 显示成功消息
                        this.$message.success('员工角色更新成功');
                    }
                },
                
                // 打开清空员工角色确认弹窗
                openClearEmployeeRolesConfirm(employee) {
                    this.currentEmployee = { ...employee };
                    this.clearEmployeeRolesConfirmVisible = true;
                },
                
                // 确认清空员工角色
                confirmClearEmployeeRoles() {
                    if (this.currentEmployee) {
                        // 记录旧角色以便更新计数
                        const oldRoles = this.currentEmployee.roles.map(r => r.id);
                        
                        // 清空员工角色
                        const employeeIndex = this.employees.findIndex(e => e.id === this.currentEmployee.id);
                        if (employeeIndex !== -1) {
                            this.employees[employeeIndex].roles = [];
                            
                            // 更新角色的员工计数
                            this.updateRoleEmployeeCounts(oldRoles, []);
                        }
                        
                        // 关闭弹窗
                        this.clearEmployeeRolesConfirmVisible = false;
                        this.currentEmployee = null;
                        
                        // 显示成功消息
                        this.$message.success('员工角色已清空');
                    }
                },
                
                // 打开向角色添加员工弹窗
                openAddEmployeeToRoleDialog() {
                    this.selectedEmployeeIds = [];
                    this.addEmployeeToRoleDialogVisible = true;
                },
                
                // 关闭向角色添加员工弹窗
                handleAddEmployeeToRoleDialogClose() {
                    this.selectedEmployeeIds = [];
                    this.addEmployeeToRoleDialogVisible = false;
                },
                
                // 确认向角色添加员工
                confirmAddEmployeeToRole() {
                    if (this.selectedEmployeeIds.length === 0) {
                        this.$message.warning('请选择要添加的员工');
                        return;
                    }
                    
                    // 获取当前角色信息
                    const roleToAdd = {
                        id: this.currentRole.id,
                        name: this.currentRole.name
                    };
                    
                    // 为选中的员工添加角色（自动去重）
                    this.selectedEmployeeIds.forEach(empId => {
                        const employeeIndex = this.employees.findIndex(e => e.id === empId);
                        if (employeeIndex !== -1) {
                            // 检查员工是否已拥有该角色
                            const hasRole = this.employees[employeeIndex].roles.some(r => r.id === roleToAdd.id);
                            if (!hasRole) {
                                this.employees[employeeIndex].roles.push(roleToAdd);
                            }
                        }
                    });
                    
                    // 更新角色的员工计数
                    this.updateRoleEmployeeCount(this.currentRole.id, this.employeesWithCurrentRole.length);
                    
                    // 关闭弹窗
                    this.handleAddEmployeeToRoleDialogClose();
                    
                    // 显示成功消息
                    this.$message.success(`已成功为${this.selectedEmployeeIds.length}名员工添加角色`);
                },
                
                // 打开从角色移除员工确认弹窗
                openRemoveEmployeeFromRoleConfirm(employee) {
                    this.employeeToRemove = { ...employee };
                    this.removeEmployeeFromRoleConfirmVisible = true;
                },
                
                // 确认从角色移除员工
                confirmRemoveEmployeeFromRole() {
                    if (this.employeeToRemove && this.currentRole) {
                        // 从员工的角色列表中移除当前角色
                        const employeeIndex = this.employees.findIndex(e => e.id === this.employeeToRemove.id);
                        if (employeeIndex !== -1) {
                            this.employees[employeeIndex].roles = 
                                this.employees[employeeIndex].roles.filter(r => r.id !== this.currentRole.id);
                            
                            // 更新角色的员工计数
                            this.updateRoleEmployeeCount(this.currentRole.id, this.employeesWithCurrentRole.length - 1);
                        }
                        
                        // 关闭弹窗
                        this.removeEmployeeFromRoleConfirmVisible = false;
                        this.employeeToRemove = null;
                        
                        // 显示成功消息
                        this.$message.success('已成功移除员工的该角色');
                    }
                },
                
                // 添加新员工相关方法
                openAddNewEmployeeDialog() {
                    this.addNewEmployeeDialogVisible = true;
                    this.employeeSelectionTab = 'byDepartment';
                    this.addEmployeeSearchQuery = '';
                    this.selectedDepartmentIds = [];
                    this.selectedEmployeeIds = [];
                    this.newEmployeeRoleIds = [];
                },
                
                handleAddNewEmployeeDialogClose() {
                    this.addNewEmployeeDialogVisible = false;
                },
                
                handleEmployeeSelectionTabChange() {
                    // 切换Tab时保留已选择的员工
                    if (this.employeeSelectionTab === 'byDepartment') {
                        // 从选择的员工反推选择的部门
                        this.selectedDepartmentIds = [];
                        const departments = [...this.departments];
                        
                        departments.forEach(dept => {
                            const employeesInDept = this.getEmployeesByDepartment(dept.id);
                            const allSelected = employeesInDept.every(emp => 
                                this.selectedEmployeeIds.includes(emp.id)
                            );
                            
                            if (allSelected && employeesInDept.length > 0) {
                                this.selectedDepartmentIds.push(dept.id);
                            }
                        });
                    }
                },
                
                handleDepartmentSelect(departmentId, selected) {
                    const employeesInDept = this.getEmployeesByDepartment(departmentId);
                    
                    if (selected) {
                        // 选中部门，添加该部门所有员工
                        employeesInDept.forEach(emp => {
                            if (!this.selectedEmployeeIds.includes(emp.id)) {
                                this.selectedEmployeeIds.push(emp.id);
                            }
                        });
                        this.selectedDepartmentIds.push(departmentId);
                    } else {
                        // 取消选中部门，移除该部门所有员工
                        employeesInDept.forEach(emp => {
                            const index = this.selectedEmployeeIds.indexOf(emp.id);
                            if (index !== -1) {
                                this.selectedEmployeeIds.splice(index, 1);
                            }
                        });
                        const index = this.selectedDepartmentIds.indexOf(departmentId);
                        if (index !== -1) {
                            this.selectedDepartmentIds.splice(index, 1);
                        }
                    }
                },
                
                getEmployeesByDepartment(departmentId) {
                    return this.employees.filter(emp => emp.departmentId === departmentId);
                },
                
                getFilteredEmployeesByDepartment(departmentId) {
                    if (!this.addEmployeeSearchQuery) {
                        return this.getEmployeesByDepartment(departmentId);
                    }
                    
                    const query = this.addEmployeeSearchQuery.toLowerCase();
                    return this.getEmployeesByDepartment(departmentId).filter(emp => 
                        emp.name.toLowerCase().includes(query)
                    );
                },
                
                getDepartmentEmployeeCount(departmentId) {
                    return this.getEmployeesByDepartment(departmentId).length;
                },
                
                confirmAddNewEmployees() {
                    // 校验
                    if (this.selectedEmployeeIds.length === 0) {
                        this.$message.error('请至少选择一个员工');
                        return;
                    }
                    
                    if (this.newEmployeeRoleIds.length === 0) {
                        this.$message.error('请至少选择一个角色');
                        return;
                    }
                    
                    // 获取所有角色信息
                    const allRoles = [...this.presetRoles, ...this.customRoles];
                    const selectedRoles = this.newEmployeeRoleIds.map(roleId => {
                        const role = allRoles.find(r => r.id === roleId);
                        return { id: role.id, name: role.name };
                    });
                    
                    // 处理选中的员工
                    this.selectedEmployeeIds.forEach(empId => {
                        const employeeIndex = this.employees.findIndex(e => e.id === empId);
                        
                        if (employeeIndex !== -1) {
                            // 员工已存在，添加新角色（去重）
                            selectedRoles.forEach(role => {
                                const hasRole = this.employees[employeeIndex].roles.some(r => r.id === role.id);
                                if (!hasRole) {
                                    this.employees[employeeIndex].roles.push(role);
                                }
                            });
                        } else {
                            // 员工不存在，创建新员工（这里仅做演示，实际应用中需要员工详细信息表单）
                            // 查找部门信息
                            let departmentInfo = null;
                            this.departments.forEach(dept => {
                                const employeesInDept = this.getEmployeesByDepartment(dept.id);
                                if (employeesInDept.some(emp => emp.id === empId)) {
                                    departmentInfo = dept;
                                }
                            });
                            
                            if (departmentInfo) {
                                const newEmployee = {
                                    id: empId,
                                    name: `新员工${empId}`, // 实际应用中应从表单获取
                                    department: departmentInfo.name,
                                    departmentId: departmentInfo.id,
                                    roles: [...selectedRoles],
                                    adder: '当前用户',
                                    addTime: new Date().toLocaleString()
                                };
                                
                                this.employees.push(newEmployee);
                            }
                        }
                    });
                    
                    // 更新角色的员工计数
                    this.newEmployeeRoleIds.forEach(roleId => {
                        const count = this.employees.filter(emp => 
                            emp.roles.some(r => r.id === roleId)
                        ).length;
                        this.updateRoleEmployeeCount(roleId, count);
                    });
                    
                    // 关闭弹窗
                    this.handleAddNewEmployeeDialogClose();
                    
                    // 显示成功消息
                    this.$message.success(`成功添加${this.selectedEmployeeIds.length}名员工，分配角色完成`);
                },
                
                // 更新角色的员工计数（批量）
                updateRoleEmployeeCounts(oldRoleIds, newRoleIds) {
                    // 找出被移除的角色
                    const removedRoles = oldRoleIds.filter(id => !newRoleIds.includes(id));
                    // 找出新增的角色
                    const addedRoles = newRoleIds.filter(id => !oldRoleIds.includes(id));
                    
                    // 更新被移除角色的计数
                    removedRoles.forEach(roleId => {
                        const count = this.employees.filter(emp => 
                            emp.roles.some(r => r.id === roleId)
                        ).length;
                        this.updateRoleEmployeeCount(roleId, count);
                    });
                    
                    // 更新新增角色的计数
                    addedRoles.forEach(roleId => {
                        const count = this.employees.filter(emp => 
                            emp.roles.some(r => r.id === roleId)
                        ).length;
                        this.updateRoleEmployeeCount(roleId, count);
                    });
                },
                
                // 更新单个角色的员工计数
                updateRoleEmployeeCount(roleId, count) {
                    // 检查是否是预设角色
                    const presetRoleIndex = this.presetRoles.findIndex(r => r.id === roleId);
                    if (presetRoleIndex !== -1) {
                        this.presetRoles[presetRoleIndex].employeeCount = `${count} 人`;
                        // 如果是当前角色，同步更新
                        if (this.currentRole.id === roleId) {
                            this.currentRole.employeeCount = `${count} 人`;
                        }
                        return;
                    }
                    
                    // 检查是否是自定义角色
                    const customRoleIndex = this.customRoles.findIndex(r => r.id === roleId);
                    if (customRoleIndex !== -1) {
                        this.customRoles[customRoleIndex].employeeCount = `${count} 人`;
                        // 如果是当前角色，同步更新
                        if (this.currentRole.id === roleId) {
                            this.currentRole.employeeCount = `${count} 人`;
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>
